from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from selenium.webdriver.common.keys import Keys
import time
import json
from datetime import datetime
import os

def load_config():
    """加载配置文件"""
    config_file = "config.json"
    default_config = {
        "search_keyword": "cosplay from china",
        "max_pages": 10,
        "output_filename": "ebay_cosplay_results",
        "browser_options": {
            "incognito": True,
            "disable_automation": True
        }
    }
    
    try:
        if os.path.exists(config_file):
            with open(config_file, 'r', encoding='utf-8') as f:
                config = json.load(f)
                print("✅ 配置文件加载成功")
                return config
        else:
            # 如果配置文件不存在，创建默认配置
            with open(config_file, 'w', encoding='utf-8') as f:
                json.dump(default_config, f, indent=4, ensure_ascii=False)
            print("⚠️ 配置文件不存在，已创建默认配置文件 config.json")
            return default_config
    except Exception as e:
        print(f"❌ 配置文件加载失败: {e}，使用默认配置")
        return default_config

# 加载配置
config = load_config()
search_keyword = config.get("search_keyword", "cosplay from china")
max_pages = config.get("max_pages", 10)
output_filename = config.get("output_filename", "ebay_cosplay_results")

# 配置Chrome浏览器的无痕模式选项
options = webdriver.ChromeOptions()
options.add_argument("--incognito")
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)

# 初始化Chrome驱动
try:
    print("正在初始化Chrome驱动...")
    
    # 首先尝试使用webdriver-manager自动安装
    try:
        service = Service(ChromeDriverManager().install())
        driver = webdriver.Chrome(service=service, options=options)
        print("✅ Chrome驱动自动安装并初始化成功")
    except Exception as e:
        print(f"⚠️ 自动安装失败: {e}")
        print("尝试使用手动安装的驱动...")
        
        # 尝试使用当前目录下的chromedriver.exe
        if os.path.exists("chromedriver.exe"):
            service = Service(executable_path="chromedriver.exe")
            driver = webdriver.Chrome(service=service, options=options)
            print("✅ 使用手动安装的Chrome驱动成功")
        else:
            # 尝试使用系统PATH中的驱动
            driver = webdriver.Chrome(options=options)
            print("✅ 使用系统PATH中的Chrome驱动成功")
    
    driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
            
except Exception as e:
    print(f"❌ Chrome驱动初始化失败: {e}")
    print("\n🔧 请按以下步骤解决驱动问题：")
    print("1. 确保已安装Chrome浏览器")
    print("2. 手动下载Chrome驱动：https://chromedriver.chromium.org/")
    print("3. 将驱动文件重命名为'chromedriver.exe'并放在此目录下")
    print("4. 或者将驱动添加到系统PATH中")
    print("5. 网络连接问题可能导致自动安装失败，请检查网络")
    exit(1)

def get_sold_quantity():
    """获取商品出售数量"""
    try:
        # 快速等待页面基本加载
        time.sleep(1)
        
        # 首先尝试查找明确的出售数量信息
        import re
        
        # 方法1: 查找包含数字和"sold"或"已售"的文本
        try:
            # 查找所有包含数字和出售关键词的元素
            elements = driver.find_elements(By.XPATH, "//*[contains(text(), 'sold') or contains(text(), '已售') or contains(text(), 'Sold') or contains(text(), 'sold')]")
            for element in elements:
                text = element.text.strip()
                if text:
                    # 使用正则表达式查找数字模式
                    # 匹配格式如: "218 sold", "1.2K sold", "1,234 sold", "已售 218"
                    patterns = [
                        r'(\d+(?:\.\d+)?[Kk]?)\s*(?:items?\s+)?sold',  # 1.2K sold, 218 sold
                        r'sold\s*(\d+(?:\.\d+)?[Kk]?)',  # sold 218
                        r'(\d+(?:,\d+)*)\s*(?:items?\s+)?sold',  # 1,234 sold
                        r'已售\s*(\d+(?:\.\d+)?[Kk]?)',  # 已售 218
                        r'(\d+(?:\.\d+)?[Kk]?)\s*已售',  # 218 已售
                    ]
                    
                    for pattern in patterns:
                        match = re.search(pattern, text, re.IGNORECASE)
                        if match:
                            sold_count = match.group(1)
                            # 处理K后缀
                            if 'k' in sold_count.lower():
                                num = float(sold_count.lower().replace('k', ''))
                                sold_count = str(int(num * 1000))
                            return f"{sold_count} sold"
        except:
            pass
        
        # 方法2: 查找常见的出售数量CSS选择器
        sold_selectors = [
            "span.vi-qtyS-hot-red",
            "span.qtyTxt",
            "span.vi-qtyS",
            "div.vi-qty-fix",
            "span.vi-qty-pur-lbl",
            "div.qty-info",
            "span.vi-qty-pur",
            "span.vi-qtyS-hot",
            "div.vi-qtyS",
            "span.vi-qtyS-hots",
            "span.vi-qtyS-hot-w",
            "div.vi-qtyS-hot",
            "span.qty-sold",
            "div.sold-quantity",
            "span.quantity-sold",
            "[data-testid='x-sellercard-sold-quantity']",
            ".sold-through-quantity",
            ".items-sold"
        ]
        
        for selector in sold_selectors:
            try:
                sold_element = driver.find_element(By.CSS_SELECTOR, selector)
                text = sold_element.text.strip()
                if text and re.search(r'\d+', text):
                    # 提取数字部分
                    numbers = re.findall(r'\d+(?:,\d+)*(?:\.\d+)?[Kk]?', text)
                    if numbers:
                        sold_count = numbers[0]
                        # 处理K后缀
                        if 'k' in sold_count.lower():
                            num = float(sold_count.lower().replace('k', ''))
                            sold_count = str(int(num * 1000))
                        return f"{sold_count} sold"
            except:
                continue
        
        # 方法3: 查找价格附近的出售信息
        try:
            price_elements = driver.find_elements(By.CSS_SELECTOR, "span[class*='price'], .vi-price, .x-price-primary")
            for price_element in price_elements:
                # 查找价格元素附近的兄弟或父元素
                nearby_elements = price_element.find_elements(By.XPATH, "./following-sibling::* | ./preceding-sibling::* | ./.. | ./../..")
                for nearby in nearby_elements:
                    text = nearby.text.strip()
                    if text and re.search(r'\d+\s*(?:sold|已售)', text, re.IGNORECASE):
                        # 提取出售数量
                        match = re.search(r'(\d+(?:,\d+)*(?:\.\d+)?[Kk]?)\s*(?:sold|已售)', text, re.IGNORECASE)
                        if match:
                            sold_count = match.group(1)
                            if 'k' in sold_count.lower():
                                num = float(sold_count.lower().replace('k', ''))
                                sold_count = str(int(num * 1000))
                            return f"{sold_count} sold"
        except:
            pass
        
        # 方法4: 查找页面中所有包含数字和出售关键词的文本
        try:
            body_text = driver.find_element(By.TAG_NAME, "body").text
            # 查找出售数量模式
            patterns = [
                r'(\d+(?:\.\d+)?[Kk]?)\s*(?:items?\s+)?sold',
                r'sold\s*(\d+(?:\.\d+)?[Kk]?)',
                r'(\d+(?:,\d+)*)\s*(?:items?\s+)?sold',
                r'已售\s*(\d+(?:\.\d+)?[Kk]?)',
                r'(\d+(?:\.\d+)?[Kk]?)\s*已售'
            ]
            
            for pattern in patterns:
                matches = re.findall(pattern, body_text, re.IGNORECASE)
                if matches:
                    sold_count = matches[0]
                    if 'k' in sold_count.lower():
                        num = float(sold_count.lower().replace('k', ''))
                        sold_count = str(int(num * 1000))
                    return f"{sold_count} sold"
        except:
            pass
            
        return "未找到出售数量信息"
    except Exception as e:
        return f"获取出售数量时出错: {str(e)}"

def get_inventory_update_info(product_url):
    """生成库存更新记录链接"""
    try:
        # 将商品详情链接中的itm替换为rvh，并截取?前面的部分
        if "ebay.com/itm/" in product_url:
            # 截取?前面的部分
            base_url = product_url.split('?')[0]
            inventory_url = base_url.replace("ebay.com/itm/", "ebay.com/rvh/")
            print(f"生成的库存更新记录链接: {inventory_url}")
            return inventory_url
        else:
            return "未找到更新记录链接"
        
    except Exception as e:
        return f"生成更新记录链接时出错: {str(e)}"

def get_product_price():
    """获取商品价格"""
    try:
        # 尝试多种CSS选择器查找价格
        price_selectors = [
            "span[class*='price']",
            ".vi-price",
            ".s-item__price",
            "span.prc",
            "div.prc",
            "span.bold",
            "span.ux-textspans",
            "div.x-price-primary"
        ]
        
        for selector in price_selectors:
            try:
                price_element = driver.find_element(By.CSS_SELECTOR, selector)
                text = price_element.text.strip()
                if text and any(char in text for char in ['$', '€', '£', '¥', '元']):
                    return text
            except:
                continue
        
        # 尝试查找包含货币符号的元素
        try:
            elements = driver.find_elements(By.XPATH, "//*[contains(text(), '$') or contains(text(), '€') or contains(text(), '£') or contains(text(), '¥') or contains(text(), '元')]")
            for element in elements:
                text = element.text.strip()
                if text and any(char in text for char in ['$', '€', '£', '¥', '元']):
                    return text
        except:
            pass
            
        return "未找到价格信息"
    except Exception as e:
        return f"获取价格时出错: {str(e)}"

def generate_html_table(products_data):
    """生成HTML表格文件"""
    html_content = f"""
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>eBay Cosplay商品搜索结果</title>
    <style>
        body {{
            font-family: Arial, sans-serif;
            margin: 20px;
            background-color: #f5f5f5;
        }}
        .container {{
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }}
        h1 {{
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }}
        table {{
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }}
        th, td {{
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }}
        th {{
            background-color: #4CAF50;
            color: white;
            position: sticky;
            top: 0;
        }}
        tr:hover {{
            background-color: #f5f5f5;
        }}
        .title-col {{
            max-width: 400px;
            word-wrap: break-word;
        }}
        .price-col {{
            font-weight: bold;
            color: #e74c3c;
        }}
        .sold-col {{
            color: #27ae60;
        }}
        .update-col {{
            color: #3498db;
            max-width: 200px;
            word-wrap: break-word;
        }}
        .info {{
            margin-bottom: 20px;
            padding: 10px;
            background-color: #e8f5e8;
            border-radius: 4px;
        }}
        /* 弹窗样式 */
        .modal {{
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }}
        .modal-content {{
            background-color: #fefefe;
            margin: 5% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
            max-width: 800px;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }}
        .close {{
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }}
        .close:hover,
        .close:focus {{
            color: black;
            text-decoration: none;
        }}
        .modal-iframe {{
            width: 100%;
            height: 500px;
            border: none;
            border-radius: 4px;
        }}
        .modal-header {{
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            border-bottom: 1px solid #ddd;
            padding-bottom: 10px;
        }}
        .modal-title {{
            font-size: 18px;
            font-weight: bold;
            color: #333;
        }}
        
        /* 查看按钮样式 */
        .revision-btn {{
            background-color: #007bff;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 3px;
            cursor: pointer;
            font-size: 12px;
            transition: background-color 0.3s;
        }}
        
        .revision-btn:hover {{
            background-color: #0056b3;
        }}
        
        .revision-btn:active {{
            background-color: #004085;
        }}
    </style>
</head>
<body>
    <!-- 弹窗 -->
    <div id="revisionModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <span class="modal-title">库存更新记录</span>
                <span class="close">&times;</span>
            </div>
            <iframe id="revisionIframe" class="modal-iframe" src=""></iframe>
        </div>
    </div>

    <div class="container">
        <h1>📦 eBay Cosplay商品搜索结果</h1>
        
        <div class="info">
            <strong>搜索关键词:</strong> {search_keyword}<br>
            <strong>搜索时间:</strong> {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}<br>
            <strong>商品数量:</strong> {len(products_data)} 个
        </div>
        
        <table>
            <thead>
                <tr>
                    <th>序号</th>
                    <th>商品标题</th>
                    <th>价格</th>
                    <th>出售数量</th>
                    <th>库存更新记录</th>
                </tr>
            </thead>
            <tbody>
    """
    
    for i, product in enumerate(products_data, 1):
        title = product.get('title', '未找到标题')
        url = product.get('url', '#')
        
        # 如果标题不是默认值且URL有效，则添加链接
        if title != '未找到标题' and url != '#':
            title_html = f'<a href="{url}" target="_blank" title="点击访问商品详情">{title}</a>'
        else:
            title_html = title
            
        # 处理库存更新记录显示
        inventory_update = product.get('inventory_update', '未找到更新记录')
        if '未找到更新记录' in inventory_update or '出错' in inventory_update:
            update_html = inventory_update
        else:
            update_html = f'<button class="revision-btn" data-url="{inventory_update}" title="点击查看更新记录">View all revisions</button>'
        
        html_content += f"""
                <tr>
                    <td>{i}</td>
                    <td class="title-col">{title_html}</td>
                    <td class="price-col">{product.get('price', '未找到价格')}</td>
                    <td class="sold-col">{product.get('sold_quantity', '未找到出售数量')}</td>
                    <td class="update-col">{update_html}</td>
                </tr>
        """
    
    html_content += """
            </tbody>
        </table>
    </div>

    <script>
        // 获取弹窗元素
        const modal = document.getElementById('revisionModal');
        const iframe = document.getElementById('revisionIframe');
        const closeBtn = document.querySelector('.close');
        
        // 获取所有查看按钮
        const revisionBtns = document.querySelectorAll('.revision-btn');
        
        // 为每个按钮添加点击事件
        revisionBtns.forEach(btn => {
            btn.addEventListener('click', function() {
                const url = this.getAttribute('data-url');
                // 在新窗口中打开链接，因为eBay阻止iframe加载
                window.open(url, '_blank');
            });
        });
        
        // 弹窗功能已移除，改为在新窗口中打开链接
    </script>
</body>
</html>
    """
    
    # 保存HTML文件
    filename = f"{output_filename}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.html"
    with open(filename, 'w', encoding='utf-8') as f:
        f.write(html_content)
    
    return filename

# 访问eBay网站并搜索
try:
    print("正在访问eBay网站...")
    driver.get("https://www.ebay.com/")
    
    # 等待页面加载
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "gh-ac"))
    )
    
    # 输入搜索关键词
    search_box = driver.find_element(By.ID, "gh-ac")
    search_box.clear()
    search_box.send_keys(search_keyword)
    
    # 尝试多种方式提交搜索
    search_submitted = False
    
    # 方式1: 点击搜索按钮
    try:
        # 尝试多种搜索按钮选择器
        search_button_selectors = [
            (By.ID, "gh-btn"),
            (By.CSS_SELECTOR, "input[type='submit']"),
            (By.CSS_SELECTOR, "button[type='submit']"),
            (By.CSS_SELECTOR, ".btn--primary"),
            (By.CSS_SELECTOR, ".btn-search"),
            (By.CSS_SELECTOR, "[aria-label*='Search']"),
            (By.XPATH, "//button[contains(text(), 'Search')]"),
            (By.XPATH, "//input[contains(@value, 'Search')]")
        ]
        
        search_button = None
        for selector in search_button_selectors:
            try:
                search_button = driver.find_element(*selector)
                break
            except:
                continue
        
        if search_button:
            search_button.click()
            search_submitted = True
            print("✅ 通过搜索按钮提交搜索")
        else:
            raise Exception("未找到有效的搜索按钮")
    except Exception as e:
        print(f"搜索按钮点击失败: {e}")
    
    # 方式2: 按回车键
    if not search_submitted:
        try:
            search_box.send_keys(Keys.RETURN)
            search_submitted = True
            print("✅ 通过回车键提交搜索")
        except Exception as e:
            print(f"回车键提交失败: {e}")
    
    # 方式3: 直接构造搜索URL
    if not search_submitted:
        try:
            # 将搜索关键词中的空格替换为+号用于URL
            search_url_keyword = search_keyword.replace(" ", "+")
            search_url = f"https://www.ebay.com/sch/i.html?_nkw={search_url_keyword}"
            driver.get(search_url)
            search_submitted = True
            print("✅ 通过直接URL访问搜索页面")
        except Exception as e:
            print(f"直接URL访问失败: {e}")
    
    if not search_submitted:
        print("❌ 所有搜索提交方式都失败了")
        driver.quit()
        exit(1)
    
    # 等待搜索结果加载
    WebDriverWait(driver, 15).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, ".srp-results"))
    )
    
    print("✅ 搜索结果页面加载成功")
    
    # 获取搜索结果数量
    try:
        results_count_element = driver.find_element(By.CSS_SELECTOR, ".srp-controls__count-heading")
        results_count = results_count_element.text
        print(f"📊 搜索结果: {results_count}")
    except:
        print("⚠️ 无法获取搜索结果数量")
    
    # 收集商品数据用于生成HTML表格
    products_data = []
    page_count = 0
    
    while page_count < max_pages:
        try:
            # 等待当前页结果加载
            WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, ".srp-results"))
            )
            
            # 获取当前页的商品链接
            link_selectors = [
                ".s-item__link",
                "a[href*='ebay.com/itm/']",
                ".s-item__info a",
                ".srp-results .s-item a",
                "[data-view*='iid'] a",
                ".s-item__wrapper a",
                "li.s-item a",
                ".srp-results li a"
            ]
            
            current_page_links = []
            for selector in link_selectors:
                try:
                    items = driver.find_elements(By.CSS_SELECTOR, selector)
                    for item in items:
                        href = item.get_attribute("href")
                        if href and "ebay.com/itm/" in href and href not in current_page_links:
                            current_page_links.append(href)
                    
                    if current_page_links:
                        break
                except:
                    continue
            
            if current_page_links:
                print(f"📄 第 {page_count + 1} 页找到 {len(current_page_links)} 个商品链接")
                
                # 立即解析当前页的商品数据
                for i, product_url in enumerate(current_page_links, 1):
                    # 跳过明显无效的链接
                    if "missing" in product_url.lower() or "error" in product_url.lower():
                        continue
                        
                    print(f"\n--- 正在访问第 {page_count + 1} 页第 {i} 个商品 ---")
                    print(f"商品链接: {product_url}")
                    
                    try:
                        # 打开新标签页访问商品详情
                        driver.execute_script(f"window.open('{product_url}', '_blank');")
                        
                        # 切换到新标签页
                        driver.switch_to.window(driver.window_handles[-1])
                        
                        # 快速等待页面基本加载
                        time.sleep(1)
                        
                        # 检查页面是否有效（不是错误页面）
                        current_url = driver.current_url
                        if "error" in current_url.lower() or "missing" in current_url.lower():
                            print("页面无效，跳过此商品")
                            driver.close()
                            driver.switch_to.window(driver.window_handles[0])
                            continue
                        
                        # 快速获取商品标题
                        product_title = "未找到标题"
                        title_selectors = [
                            (By.CSS_SELECTOR, "h1[class*='title']"),
                            (By.CSS_SELECTOR, ".vi-title"),
                            (By.CSS_SELECTOR, "h1.it-ttl"),
                            (By.CSS_SELECTOR, "h1.x-item-title"),
                            (By.CSS_SELECTOR, "h1.item-title"),
                            (By.CSS_SELECTOR, "h1.s-item__title"),
                            (By.XPATH, "//h1[contains(@class, 'title')]"),
                            (By.CSS_SELECTOR, "h1")
                        ]
                        
                        for selector in title_selectors:
                            try:
                                title_element = driver.find_element(*selector)
                                title_text = title_element.text.strip()
                                if title_text and len(title_text) > 5 and "missing" not in title_text.lower():
                                    product_title = title_text
                                    print(f"商品标题: {product_title}")
                                    break
                            except:
                                continue
                        
                        if product_title == "未找到标题":
                            print("未找到商品标题，可能为无效页面")
                            driver.close()
                            driver.switch_to.window(driver.window_handles[0])
                            continue
                        
                        # 快速获取商品价格
                        product_price = get_product_price()
                        print(f"商品价格: {product_price}")
                        
                        # 快速获取出售数量
                        sold_quantity = get_sold_quantity()
                        print(f"出售数量: {sold_quantity}")
                        
                        # 获取库存更新记录信息
                        inventory_update_info = get_inventory_update_info(product_url)
                        print(f"库存更新记录: {inventory_update_info}")
                        
                        # 收集商品数据
                        product_data = {
                            'title': product_title,
                            'price': product_price,
                            'sold_quantity': sold_quantity,
                            'inventory_update': inventory_update_info,
                            'url': product_url
                        }
                        products_data.append(product_data)
                        
                        # 立即关闭当前标签页
                        driver.close()
                        
                        # 切换回主标签页（搜索结果页面）
                        driver.switch_to.window(driver.window_handles[0])
                        
                        # 短暂等待再处理下一个商品
                        time.sleep(1)
                        
                    except Exception as e:
                        print(f"访问商品时出错: {str(e)}")
                        
                        # 确保切换回主标签页
                        try:
                            driver.switch_to.window(driver.window_handles[0])
                        except:
                            pass
                            
            else:
                print(f"⚠️ 第 {page_count + 1} 页未找到商品链接")
            
            # 尝试点击下一页
            try:
                next_button_selectors = [
                    "a.pagination__next",
                    "a[rel='next']",
                    "a[aria-label*='next']",
                    "a[class*='next']",
                    "button[class*='next']",
                    "//a[contains(text(), 'Next')]",
                    "//a[contains(text(), '下一页')]"
                ]
                
                next_found = False
                for selector in next_button_selectors:
                    try:
                        if selector.startswith("//"):
                            next_button = driver.find_element(By.XPATH, selector)
                        else:
                            next_button = driver.find_element(By.CSS_SELECTOR, selector)
                        
                        if next_button.is_enabled():
                            driver.execute_script("arguments[0].click();", next_button)
                            page_count += 1
                            next_found = True
                            print(f"➡️ 正在跳转到第 {page_count + 1} 页")
                            time.sleep(3)  # 等待页面跳转
                            break
                    except:
                        continue
                
                if not next_found:
                    print("✅ 已到达最后一页")
                    break
                    
            except Exception as e:
                print(f"⚠️ 翻页失败: {e}")
                break
                
        except Exception as e:
            print(f"⚠️ 处理第 {page_count + 1} 页时出错: {e}")
            break
    
    print(f"🔗 总共处理了 {len(products_data)} 个商品")
    
    if not products_data:
        print("❌ 未找到有效的商品数据")
        driver.quit()
        exit(1)

except Exception as e:
    print(f"❌ 访问eBay网站失败: {e}")
    driver.quit()
    exit(1)

print("\n=== 商品详情访问完成 ===")

# 生成HTML表格文件
if products_data:
    html_filename = generate_html_table(products_data)
    print(f"\n✅ HTML表格已生成: {html_filename}")
    print("📊 商品数据汇总:")
    for i, product in enumerate(products_data, 1):
        print(f"   {i}. {product['title']} - {product['price']} - {product['sold_quantity']} - {product['inventory_update']}")
else:
    print("⚠️ 未找到有效商品数据，无法生成HTML表格")

# 保持浏览器打开状态一段时间，以便查看结果
print("浏览器将保持打开10秒钟...")
time.sleep(10)

# 关闭浏览器
if driver is not None:
    driver.quit()
    print("浏览器已关闭")